<template>
	<view class="homeLayout">
		<view class="head">
			<home-head></home-head>
		</view>

		<view class="body">
			<view class="swiperOut">
				<view class="noData" v-if="!listData.length">
					<uni-load-more status="loading" :showText="false"></uni-load-more>
				</view>
				<swiper vertical @change="swiperChange" :duration="260" v-else>
					<swiper-item v-for="(item,index) in listData" :key="index">
						<navigator :url="`/pages/detailSoup/detailSoup?id=${item._id}`" class="content">
							<soup-tab-group :type="item.soup_type"></soup-tab-group>

							<soup-text-content maxline="5" :item="item"></soup-text-content>
						</navigator>
						<interactive-tab :item="item" @share="clickShare(index)"></interactive-tab>
					</swiper-item>


					<swiper-item class="ad">
						<view class="message">
							<view class="title">恭喜您，今日健康小知识已干完！</view>
							<!-- <text class="des">每日5碗鸡汤，如果想要加餐，\n点击下方看广告按钮，可继续推送5碗，\n每日最多加餐5次。</text> -->
							<text class="des">学一点饮食知识，多一份健康底气，舌尖上的智慧，是对自己最长久的疼爱。</text>
						</view>
						<!-- 	<view class="btnGroup">
							<view class="btn" @click="clickAdSoup">看广告刷新</view>
							<view class="text">今日还有{{readNumber}}次机会</view>
						</view> -->
						<view class="ig">
							<image src="../../static/images/美食.jpg" mode="aspectFill"></image>
						</view>
					</swiper-item>

				</swiper>
			</view>
			<view class="progress">
				<view class="line" :style="{width:lineWidth+'%'}"></view>
			</view>

		</view>

		<uni-popup ref="usePopup" type="center" @maskClick="closeUsePopup" @touchmove="closeUsePopup">
			<view class="usePopup">
				<image src="../../static/images/upward.png" mode="heightFix" @click="closeUsePopup"></image>
			</view>
		</uni-popup>

		<share-posters ref="shareRef" :info="shareInfo"></share-posters>
	</view>
</template>

<script setup>
	import {
		computed,
		ref
	} from 'vue';
	import {
		onReady
	} from "@dcloudio/uni-app"
	import {
		useCounterStore
	} from "@/stores/counter.js";
	import {
		showToast
	} from '../../utils/common';
	const counterStore = useCounterStore()
	const listData = ref([]);
	const currentIndex = ref(0);
	const usePopup = ref(null);
	const db = uniCloud.database();
	const dbCmd = db.command;
	const $ = dbCmd.aggregate;
	const currentUser = uniCloud.getCurrentUserInfo().uid
	const readNumber = ref(5);
	const shareRef = ref(null)
	const shareInfo = ref(null);
	//用于表示进度条的宽度 
	const lineWidth = computed(() => (currentIndex.value) / (listData.value.length) * 100)
	//生命钩子  页面全部渲染完成之后展示遮罩层
	onReady(() => {
		//设置 一个 变量控制 遮罩层
		let usePopupState = uni.getStorageSync('usePopup') || false
		if (!usePopupState) usePopup.value.open()
	})

	//点击分享
	const clickShare = (index) => {
		shareInfo.value = listData.value[index]
		shareRef.value.handleShow();
	}

	//获取鸡汤
	const getSoup = async (type = 'get') => {
		// 查询soup - today表， 有无当前用户进入的记录
		let {
			result: {
				data: todayData = [],
				errCode = -1
			} = {}
		} = await db.collection("soup-today").where(`user_id == $cloudEnv_uid`).get();
		// 存在today记录， 就获取today的鸡汤
		if (todayData.length && type == 'get') {
			if (errCode != 0) return showToast("信息有误，请重新刷新", "none");
			listData.value = [...listData.value, ...todayData[0].soup_list];
			readNumber.value = todayData[0].number;
		} else {
			//不存在则执行查询soup-chicken中满足要求的鸡汤
			let {
				result: {
					errCode,
					data
				}
			} = await db.collection("soup-jt").aggregate()
				.lookup({
					from: "soup-user-read", //连接的表名
					let: {
						soupID: '$_id'
					},
					pipeline: $.pipeline().match(dbCmd.expr($.eq(['$user_id', currentUser])))
						.project({ //pipeline 表示通道
							soup_id: 1
						}).done(),
					as: "readSoup"
				})
				.addFields({ //输出返回 在原字段增加新的字段
					readSoup: $.map({
						input: "$readSoup",
						in: "$$this.soup_id"
					})
				})
				.match({ //筛选过滤
					status: 1,
					is_delete: dbCmd.neq(true) //neq表示不等于
				})
				.match(dbCmd.expr(
					$.cond({
						if: $.eq([type, 'random']),
						then: $.in(["$_id", '$readSoup']),
						else: $.not($.in(["$_id", '$readSoup']))
					})
				))
				.lookup({
					from: "uni-id-users",
					let: {
						uid: '$user_id'
					},
					pipeline: $.pipeline().match(dbCmd.expr($.eq(['$_id', '$$uid']))).project({
						username: 1,
						avatar: 1
					}).done(), //done表示结束查询 project表示过滤
					as: "userInfo"
				})

				.sample({ //随机数
					size: 5
				})
				.limit(5)
				.project({ //arrayElemAt 表示 根据索引获取数组的值
					isLike: $.cond({
						if: $.gt([$.arrayElemAt(['$likeState.length', 0]), 0]),
						then: true,
						else: false
					}),
					collect_count: 1,
					comment_count: 1,
					content: 1,
					from: 1,
					like_count: 1,
					soup_type: 1,
					view_count: 1,
					userInfo: $.arrayElemAt(['$userInfo', 0])
				})
				.end()

			if (errCode != 0) return showToast("信息有误，请重新刷新", "none");

			if (data.length == 0) return getSoup("random");

			data[0].is_read = true;
			listData.value = [...listData.value, ...data];
			if (type == 'ad') {
				db.collection("soup-today").where(`user_id == "${currentUser}"`).update({
					soup_list: listData.value
				})
			} else {
				db.collection("soup-today").add({
					user_id: currentUser,
					soup_list: data
				})
			}
			uni.hideLoading();
			// console.log(data);
			// console.log("123");
		}

	}
	getSoup()

	//轮播切换事件
	const swiperChange = (e) => {
		currentIndex.value = e.detail.current
		//判断 是否已经 看过
		if (listData.value[currentIndex.value] && !listData.value[currentIndex.value].is_read) {
			listData.value[currentIndex.value].is_read = true;
			db.collection("soup-today").where(`user_id == $cloudEnv_uid`).update({
				soup_list: listData.value
			}).then(res => {
				console.log(res);
			})
		} else {
			// console.log("重复操作");
		}
	}

	//点击广告
	//点赞
	uni.$on('like', (e) => {
		console.log(e);
		let index = listData.value.findIndex(item => item._id == e._id);
		listData.value[index] = {
			...listData.value[index],
			...e
		}
		db.collection("soup-today").where(`user_id == $cloudEnv_uid`).update({
			soup_list: listData.value
		})
	})

	//点击取消遮罩层
	const closeUsePupop = () => {
		uni.setStorageSync("usePopup", true)
		usePopup.value.close();
	}
</script>

<style lang="scss" scoped>
	.homeLayout {
		height: 100vh;
		background: #BDE1FB;
		display: flex;
		flex-direction: column;

		.head {}

		.body {
			flex: 1;
			background: #fff;
			border-radius: 50rpx 50rpx 0 0;
			overflow: hidden;

			.swiperOut {
				height: calc(100% - 8rpx);

				.noData {
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				swiper {
					height: 100%;

					&-item {
						.content {
							height: calc(100% - 130rpx);
							display: flex;
							justify-content: center;
							flex-direction: column;
							padding: 0 30rpx;





						}

					}

					.ad {
						background: #F8F8F8;
						padding: 100rpx 30rpx;
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						align-items: center;
						text-align: center;

						.message {
							background: #fff;
							border-radius: 30rpx;
							padding: 40rpx;

							.title {
								font-size: 46rpx;
								padding-bottom: 20rpx;
								border-bottom: 1px solid #eee;
								margin-bottom: 20rpx;
							}

							.des {
								font-size: 32rpx;
								color: #319566;
								line-height: 1.8em;
							}

						}

						.ig {
							height: 600rpx; // 设置固定高度，可根据需求调整
							width: 100%;
							overflow: hidden;
							// margin-bottom: 10rpx;

							image {
								width: 100%;
								height: 100%;
								object-fit: cover; // 确保图片覆盖整个容器
							}
						}

						.btnGroup {
							font-size: 30rpx;

							.btn {
								width: 400rpx;
								height: 100rpx;
								border-radius: 100rpx;
								background: linear-gradient(to top, #93c4ff, #b1e1ff);
								display: flex;
								justify-content: center;
								align-items: center;
								font-size: 38rpx;
								color: #203e5f;
								margin-bottom: 10rpx;
							}

							.text {
								padding: 20rpx 0;
							}
						}
					}

				}
			}

			.progress {
				height: 8rpx;
				width: 100%;
				background: #eee;

				.line {
					height: 100%;
					width: 0%;
					background: linear-gradient(to right, #BCE0FD, #74dbef);
				}
			}
		}
	}


	.usePopup {
		padding-top: 15vh;

		image {
			height: 150rpx;
			transform: translateY(100rpx);
			opacity: 0;
			animation: useanimate 1.5s infinite;
		}
	}

	@keyframes useanimate {
		0% {
			transform: translateY(100rpx);
			opacity: 0;
		}

		100% {
			transform: translateY(-100rpx);
			opacity: 1;
		}
	}
</style>